<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>
          <el-button
            icon="el-icon-plus"
            size="small"
            type="primary"
            round
            @click="openDrawer('add')"
          >
            添加面经
          </el-button>
        </div>
      </template>

      <!-- table表格数据区域 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        stripe
        border
        v-loading="loading"
      >
        <el-table-column prop="stem" label="标题" width="240" fixed>
        </el-table-column>
        <el-table-column prop="creator" label="作者" width="180">
        </el-table-column>
        <el-table-column prop="likeCount" label="点赞"> </el-table-column>
        <el-table-column prop="views" label="浏览数"> </el-table-column>
        <el-table-column prop="createdAt" label="更新时间"> </el-table-column>
        <el-table-column label="操作">
          <!-- 表格子项的作用域插槽 -->
          <template #default="{ row }">
            <div class="actions">
              <i
                class="el-icon-view"
                @click="openDrawer('preview', row.id)"
              ></i>
              <i
                class="el-icon-edit-outline"
                @click="openDrawer('edit', row.id)"
              ></i>
              <i class="el-icon-delete" @click="del(row.id)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- table表格数据区域 -->

      <!-- 分页组件区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryObj.current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryObj.pageSize"
        layout="sizes, prev, pager, next,total"
        :total="total"
      >
      </el-pagination>
      <!-- 分页组件区域 -->
    </el-card>

    <!-- 抽屉组件 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="isDrawerShow"
      direction="rtl"
      :before-close="handleClose"
      size="50%"
    >
      <div v-if="drawerType === 'preview'" class="article-preview">
        <h5>{{ form.stem }}</h5>
        <div v-html="form.content"></div>
      </div>
      <el-form
        v-else
        ref="form"
        label-width="80px"
        :model="form"
        :rules="rules"
      >
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem" placeholder="输入面经标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <quillEditor
            v-model="form.content"
            @blur="$refs.form.validateField('content')"
          ></quillEditor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addOrUpdateArticle">确认</el-button>
          <el-button @click="handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 抽屉组件 -->
  </div>
</template>

<script>
import {
  getArticleList,
  addArticleList,
  delArticleList,
  getArticle,
  updateArticle
} from '@/api/article'

// 引入富文本组件
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'

export default {
  name: 'ArticleIndex',
  components: {
    quillEditor
  },

  data () {
    return {
      tableData: [
        {
          date: '2016-05-02',
          username: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        },
        {
          date: '2016-05-04',
          username: '王小虎',
          address: '上海市普陀区金沙江路 1517 弄'
        },
        {
          date: '2016-05-01',
          username: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄'
        },
        {
          date: '2016-05-03',
          username: '王小虎',
          address: '上海市普陀区金沙江路 1516 弄'
        }
      ],
      queryObj: {
        current: 1, // 控制当前页
        pageSize: 10 // 控制每页有几条数据
      },
      form: {
        stem: '',
        content: ''
      },
      id: 0,

      // 验证规则
      rules: {
        stem: [{ required: true, message: '请输入面经标题', trigger: 'blur' }],
        content: [
          { required: true, message: '请输入面经内容', trigger: 'blur' }
        ]
      },

      total: 0,
      isDrawerShow: false, // 控制抽屉组件的开关
      drawerType: 'add',
      loading: false
    }
  },
  created () {
    this.initTable()
  },
  methods: {
    // 点击删除图标删除对应数据
    async del (id) {
      // TODO 删除事件
      try {
        await delArticleList(id)

        this.$message.success('删除成功')

        this.initTable()
      } catch (error) {
        this.$message.error('删除失败')
      }
    },

    // 获取table数据
    async initTable () {
      this.loading = true
      const { data } = await getArticleList(this.queryObj)

      // console.log(data.rows)
      this.tableData = data.rows
      this.total = data.total
      this.loading = false
    },

    // pageSize 改变时会触发
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.queryObj.pageSize = val
      this.queryObj.current = 1
      this.initTable()
    },

    // current当前页改变时会触发
    async handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      // 改变参数对象中的当前页
      this.queryObj.current = val
      this.initTable()
    },

    // 抽屉组件关闭之前触发
    handleClose () {
      // 把表单的数据还原
      this.form.stem = ''
      this.form.content = ''

      // 重置表单
      if (this.drawerType !== 'preview') {
        // add edit 调用 resetFields 在此处的作用: 重置校验状态
        this.$refs.form.resetFields()
      }

      this.isDrawerShow = false
    },

    // 打开抽屉
    async openDrawer (type, id) {
      this.drawerType = type

      // 编辑功能
      if (type !== 'add') {
        const { data } = await getArticle(id)

        console.log(data)

        this.form.stem = data.stem
        this.form.content = data.content
        this.id = data.id
      }
      this.isDrawerShow = true
    },

    // 添加面经事件
    // 修改面经事件
    async addOrUpdateArticle () {
      // 表单的非空验证
      try {
        await this.$refs.form.validate()

        if (this.drawerType === 'add') {
          // 发起添加请求
          await addArticleList(this.form)
        }
        if (this.drawerType === 'edit') {
          // 发起添加请求
          await updateArticle({ id: this.id, ...this.form })
        }

        // 清空表单
        this.form.stem = ''
        this.form.content = ''

        // 关闭抽屉组件
        this.isDrawerShow = false
        // 提示用户
        this.$message.success(
          this.drawerType === 'add' ? '添加成功' : '修改成功'
        )

        // 重新获取新的数据渲染页面
        this.initTable()
      } catch (error) {
        this.$message.error('请输入必填项')
      }
    }
  },
  computed: {
    drawerTitle () {
      if (this.drawerType === 'add') return '添加面经'
      if (this.drawerType === 'edit') return '编辑面经'
      if (this.drawerType === 'preview') return '预览面经'
      else {
        return 'add'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
